package com.huawei.fakedouyin.util

import android.content.Context
import android.util.Base64
import com.huawei.fakedouyin.base.BaseApplication
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.ObjectInputStream
import java.io.ObjectOutputStream

/**
 * 日期：2022/9/7
 * 作者：wyt
 * 备注：君子以厚德载物
 */
class SPUtil private constructor() {
    companion object {
        val Instance by lazy { SPUtil() }
    }

    private val sp = BaseApplication.Instance.getSharedPreferences(
        BaseApplication.Instance.packageName,
        Context.MODE_PRIVATE
    )

    //SP写入String
    fun put(key: String, value: String?) {
        sp.edit().putString(key, value).apply()
    }

    //SP中写入Int
    fun put(key: String, value: Int) {
        sp.edit().putInt(key, value).apply()
    }


    //SP中写入Long
    fun put(key: String, value: Long) {
        sp.edit().putLong(key, value).apply()
    }

    //SP写入Set<String>
    fun put(key: String, value: Set<String?>) {
        sp.edit().putStringSet(key, value).apply()
    }

    //SP写入Boolean
    fun put(key: String, value: Boolean) {
        sp.edit().putBoolean(key, value).apply()
    }

    /**保持对象，记得开线程*/
    fun putObject(key: String, obj: Any) {
        val bao = ByteArrayOutputStream()
        val oos = ObjectOutputStream(bao)
        oos.writeObject(obj)

        //将对象转成byte数组，并进行Base64编码
        val objectStr = String(Base64.encode(bao.toByteArray(), Base64.DEFAULT))
        bao.close()
        oos.close()
        put(key, objectStr)
    }

    fun getString(key: String, default: String = ""): String {
        return sp.getString(key, default) ?: ""
    }

    fun getInt(key: String, default: Int = 0): Int {
        return sp.getInt(key, default)
    }

    fun getLong(key: String, default: Long = 0L): Long {
        return sp.getLong(key, default)
    }

    fun getBoolean(key: String, default: Boolean = false): Boolean {
        return sp.getBoolean(key, default)
    }

    fun getStringSet(key: String): Set<String?>? {
        return sp.getStringSet(key, emptySet<String>())
    }

    /**获取保存的对象，记得开线程*/
    fun getObject(key: String): Any? {
        val base64 = getString(key)
        if (base64.isEmpty()) {
            return null
        }
        val objBytes = Base64.decode(base64.toByteArray(), Base64.DEFAULT)
        val bai = ByteArrayInputStream(objBytes)
        val ois = ObjectInputStream(bai)

        val obj = ois.readObject()
        bai.close()
        ois.close()
        return obj
    }

    //清空SP中所有数据
    fun clear() {
        sp.edit().clear().apply()
    }
}